package com.ohuang.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/**
 * socket的服务器
 */
public class SocketTest {
    private static final int PORT = 3456;
    private List<Socket> mList = new ArrayList<>();
    private List<Service>  serviceList=new LinkedList<>();
    private ServerSocket server = null;
    private ExecutorService mExecutorService = null;
    private String receiveMsg;
    private String sendMsg;




    public SocketTest() {
        try {
            server = new ServerSocket(PORT);
            mExecutorService = Executors.newCachedThreadPool();
            System.out.println("服务器已启动...");
            Socket client = null;
            while (true) {
                client = server.accept();
                mList.add(client);
                Service service=new Service(client);
                serviceList.add(service);
                mExecutorService.execute(service);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class Service implements Runnable {
        private Socket socket;
        private BufferedReader in = null;
        private PrintWriter printWriter = null;

        public Service(Socket socket) {
            this.socket = socket;
            try {
                printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")), true);
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream(), "UTF-8"));
                printWriter.println("成功连接服务器" + "（服务器发送）");
                System.out.println("成功连接服务器");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        public void print(String s){
            printWriter.println(s);
        }

        public void remove(){
            serviceList.remove(this);
        }


        @Override
        public void run() {
            try {
                while (true) {
                    if ((receiveMsg = in.readLine()) != null) {
                        System.out.println("receiveMsg:" + receiveMsg);
                        if (receiveMsg==null){
                            continue;
                        }
                        if (receiveMsg.equals("0")) {
                            System.out.println("客户端请求断开连接");
                            printWriter.println("服务端断开连接" + "（服务器发送）");
                            mList.remove(socket);
                            remove();
                            in.close();
                            socket.close();
                            break;
                        } else {
                            sendMsg =socket.toString()+":"+ receiveMsg;
                            serviceList.forEach(new Consumer<Service>() {
                                @Override
                                public void accept(Service service) {
                                    service.print(sendMsg);
                                }
                            });
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
